class Enlarge
{
    constructor(el)
    {
        this.el = document.querySelector(el)
        this.img = this.el.querySelector('.img')
        this.mask = this.el.querySelector('.mask')
        this.enlarge = this.el.querySelector('.enlarge')
        this.small = this.el.querySelectorAll('ul li')
        this.init()
    }
    
    init() {
        this.overOut()
        this.enlargeWH()
        this.maskMove()
        this.tbEnlarge()
        this.smallImg()
    }
    getStyle(tagObj,cssAttr){
        if(window.getComputedStyle){
            return getComputedStyle(tagObj)[cssAttr]
        } else {
            return tagObj.currentStyle[cssAttr]
        }
    }
    overOut() {
        this.img.onmouseover = () => this.mask.style.display = this.enlarge.style.display = 'block'
        this.img.onmouseout = () => this.mask.style.display = this.enlarge.style.display = 'none'
    }
    enlargeWH() {
        let enlarge = this.getStyle(this.enlarge,'background-size')
        let enlargeW = parseInt(enlarge.split(' ')[0])
        let enlargeH = parseInt(enlarge.split(' ')[1])
        let imgW = this.img.clientWidth
        let imgH = this.img.clientHeight
        let maskW = parseInt(this.getStyle(this.mask,'width'))
        let maskH = parseInt(this.getStyle(this.mask,'height'))
        this.enlarge.style.width = maskW * (enlargeW / imgW) + 'px'
        this.enlarge.style.height = maskH * (enlargeH / imgH)  + 'px'
    }
    maskMove() {
        this.img.onmousemove = (evt) => {
            let e = evt || window.event
            let x = e.pageX - this.el.offsetLeft - this.mask.offsetWidth/2
            let y = e.pageY - this.el.offsetTop - this.mask.offsetHeight/2
            if(x<0) x=0
            if(y<0) y=0
            let maxLeft = this.img.offsetWidth - this.mask.offsetWidth
            let maxTop = this.img.offsetHeight - this.mask.offsetHeight
            if(x>maxLeft) x=maxLeft
            if(y>maxTop) y=maxTop
            this.mask.style.left = x + 'px'
            this.mask.style.top = y + 'px'
            this.tbEnlarge(x,y)
        }
    }
    tbEnlarge(x,y) {
        let enlargeW =  parseInt(this.enlarge.style.width)
        let maskW = this.mask.offsetWidth
        let data = enlargeW / maskW
        this.enlarge.style.backgroundPosition = `-${x*data}px -${y*data}px`
    }
    smallImg() {
        this.small.forEach((item,i)=>{
            item.onclick = () => {
                this.img.style.background = `url(./imgs/${i+1}.jpg)`
                this.enlarge.style.background = `url(./imgs/${i+1}.big.jpg)`
                this.el .querySelector('.active').className = ''
                item.className = 'active'
            }
        })
    }
}
export default Enlarge